/*
 * #depends user-preferences-store.js
 */
/*global window: false*/
Ext.ux.mattgoldspink.subsonic.FolderTracksStore = new Ext.data.ArrayStore({
    // reader configs
    restful: true,
    autoDestroy: false,
    idIndex: 0,
    sortInfo: {
        field: 'album',
        direction: 'ASC'
    },
    fields: Ext.ux.mattgoldspink.subsonic.Fields,
    loadingIcon:new Ext.XTemplate(
        'Loading... Rendered {rowsRendered} of {rowsRemaining} rows'
    ),
    workerCount: 10,
    rowCountToProcess: Ext.ux.mattgoldspink.subsonic.UserPrefsStore.get('track-grid-batch-size', 50),
    currentWorker: 0,
    pendingRecords: [],
    getNextWorker: function(){
        if (++this.currentWorker >= this.workerCount) {
            this.currentWorker = 0;
        }
        return $.Hive.get(this.currentWorker);
    },
    removeAllIncludingPending: function(){
		this.requestId = Ext.id();
        this.pendingRecords = [];
        this.removeAll();
    },
    load: function(data){
        this.workerLoad(data.params.id, false, true);
    },
	setPlaylistMode: function(){
		this.url = Ext.ux.mattgoldspink.subsonic.apiUrl + '/rest/getPlaylist.view';
	},
	setFolderMode: function(){
		this.url = Ext.ux.mattgoldspink.subsonic.apiUrl + '/rest/getMusicDirectory.view';
	},
    search: function(searchString, searchType) {
        this.fireEvent('beforeload', this);
        this.removeAllIncludingPending();
        this.getNextWorker().send({ 
            "message" : {
                "c": Ext.ux.mattgoldspink.subsonic.LoginDetails.c,
                "v": Ext.ux.mattgoldspink.subsonic.LoginDetails.v,
                "u": Ext.ux.mattgoldspink.subsonic.LoginDetails.u,
                "p": Ext.ux.mattgoldspink.subsonic.LoginDetails.p,
                "f" : 'json',
                "artistCount" : 200,
				"albumCount" : 200,
				"songCount" : 200,
                "query" : searchString+'*'
            },
            "url" : Ext.ux.mattgoldspink.subsonic.apiUrl + '/rest/search2.view',
			"searchType": searchType,
			"requestId": this.requestId
        });            
    },
    workerLoad: function(id, add, recursive) {
        this.fireEvent('beforeload', this);
        if ((add === false || add === undefined) && this.data) {
            this.removeAllIncludingPending();
        }
        this.getNextWorker().send({ 
            "message" : {
                "c": Ext.ux.mattgoldspink.subsonic.LoginDetails.c,
                "v": Ext.ux.mattgoldspink.subsonic.LoginDetails.v,
                "u": Ext.ux.mattgoldspink.subsonic.LoginDetails.u,
                "p": Ext.ux.mattgoldspink.subsonic.LoginDetails.p,
                "id" : id,
                "f" : 'json'
            },
            "url" : this.url, 
            "recursive": recursive,
			"requestId": this.requestId
        });
    },
    processPendingRecords: function(){        
        var i = (this.pendingRecords.length >= this.rowCountToProcess? this.rowCountToProcess: this.pendingRecords.length ), records = [];
        if (i > 0) {
            var totalCount = this.getCount();
            window.Ext.ux.Bus.fireEvent('message', 'subsonic.status', {
                 text: this.loadingIcon.apply({'rowsRendered': totalCount, 'rowsRemaining': this.pendingRecords.length + totalCount})
            });
            Ext.each(this.pendingRecords.splice(0, i), function(item) {
                var rec = new Ext.ux.mattgoldspink.subsonic.FolderTracksStore.recordType(item, item.id);
                if (rec !== undefined) {
                    records.push(rec);
                }
            });
            if (records.length > 0) {
                this.add(records);
                var sortState = this.getSortState();
                this.sort(sortState.field, sortState.direction);
                this.fireEvent('load', this);
            }
          }
          if (this.pendingRecords.length === 0){
            window.Ext.ux.Bus.fireEvent('message', 'subsonic.status.clear', {});
          }
    },
    listeners: {
        load: function(store, records, options){
            Ext.each(records, function(record) {
                if (record.get('isDir')){
                    this.remove(record);
                }
            }, Ext.ux.mattgoldspink.subsonic.FolderTracksStore);
        }
    }
});

$.Hive.create({
	count: Ext.ux.mattgoldspink.subsonic.FolderTracksStore.workerCount,  
	worker: 'desktop/subsonic-worker-loader.js',
	receive: function (data) {
		if (data.results && data.requestId === Ext.ux.mattgoldspink.subsonic.FolderTracksStore.requestId) {
			Ext.each(data.results, function(item){
				if (item.isDir && data.recursive) {
					Ext.ux.mattgoldspink.subsonic.FolderTracksStore.workerLoad(item.id, true, data.recursive);
				} else if (data.requestId === Ext.ux.mattgoldspink.subsonic.FolderTracksStore.requestId) {
					Ext.ux.mattgoldspink.subsonic.FolderTracksStore.pendingRecords.push(item);
				}
			});
		}
	},
	error: function(e) {
	}
});

Ext.ux.mattgoldspink.subsonic.SelectedItem = new Ext.Panel({
    width: 250,
    height: 250,
    cls: 'album-view',
    title: 'Selected Item',
    tpl: new Ext.XTemplate(
        '<div class="thumb-wrap" id="{title}">',
        '<div class="thumb"><img src="{[ this.makeUrl(values.coverArt)]}" title="{title}" id="{id}" type="{isDir}" /></div>',
        '<span class="x-editable title">{title}</span>',
        '<span class="x-editable artist">{artist}</span>',
        '<span class="x-editable album">{album}</span>',
        '</div>',
        '<div class="x-clear"></div>',
        {
            makeUrl: function(coverArt) {
                var params = {
                    size: '100'
                };
                Ext.apply(params, Ext.ux.mattgoldspink.subsonic.LoginDetails);
                params.id = coverArt;
                return Ext.ux.mattgoldspink.subsonic.apiUrl + '/rest/getCoverArt.view?' + Ext.urlEncode(params);
            }
        }),
   plugins: ['msgbus'],
   listeners: {
        afterrender: function(){
            this.subscribe('subsonic.track.nowplaying', {fn: function(subject, track){
                this.update(track);
            }, scope: this});
        }
   }
});

Ext.TaskMgr.start({
    run: Ext.ux.mattgoldspink.subsonic.FolderTracksStore.processPendingRecords,
    scope: Ext.ux.mattgoldspink.subsonic.FolderTracksStore,
    interval: 2000 //5 second
});
